import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import {ElMessage} from 'element-plus'
import {staticRoutes} from '@/router/routes'
import { reqLogin ,reqUserInfo,reqLogOut} from '@/api/acl/login';


/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

	state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: []
  }),

	actions: {
    // 登录请求:成功则返回token
  async  login (username: string, password: string) {
   try {
    // 登录成功
    let result = await reqLogin({username,password})
    // 仓库存储token
    this.token = result.token
    // 持久化存储
    setToken(result.token)
    return 'ok'
   } catch (error) {
    return Promise.reject('失败')
   }
    },

    // 获取用户信息
  async  getInfo () {
      try {
        // 发生请求,请求头记得带token
        let result = await reqUserInfo()
        // 获取用户信息并存储
        this.name = result.name
        this.avatar = result.avatar
        this.menuRoutes = staticRoutes
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 退出登录
   async reset () {
     try {
      await reqLogOut()
       // 删除local中保存的token
       removeToken()
       // 提交重置用户信息的mutation
       this.token = ''
       this.name = ''
       this.avatar = ''
       return 'ok'
     } catch (error) {
      return Promise.reject(error)
      
     }
    },
	},
});
